home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 6995 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.5 KB

  1. Path: li.net!sbda
  2. From: sbda@newshost.li.net (sbda)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How to tell if a file exists in C
  5. Date: 17 Feb 1996 02:11:51 GMT
  6. Organization: LI Net (Long Island Network)
  7. Message-ID: <4g3dh7$co6@linet06.li.net>
  8. References: <823685019.AA00170@escan.demon.co.uk>
  9. NNTP-Posting-Host: linet01.li.net
  10. X-Newsreader: TIN [version 1.2 PL2]
  11.  
  12. Bill Birrell (bill@escan.demon.co.uk) wrote:
  13. :  > Hi, how do I find out if a file already exists
  14. :  > in UNIX C? On PCs I would do a findfirst/findnext,
  15. :  > is there an equivalent on Unix?
  16.  
  17. :     Check up on access() and stat(). There cannot be an exact equivalent to
  18. : Digital Research's findfirst and findnext functions in unix, because unix has
  19. : a completely different file structure from CP/M or PC-Dos (later MsDos), and
  20. : therefore has no idea what FCBs are. Files, directories and devices are all
  21. : accessed the same way, and when you become used to it, it is a *much* simpler
  22. : and more logical approach. Take a look at K&R Chapter 8 [Either edition - it's
  23. : in both].
  24.  
  25. : Bill.
  26.  
  27.  
  28. : --
  29. : Regards,
  30. : Bill Birrell.
  31. : internet:       bill@escan.demon.co.uk
  32.  
  33.  
  34. Here's another way - it's ANSI C - so it should work on all C compilers 
  35. and on all OSes:
  36.  
  37. /*---------------------------------------*/
  38. FILE *fp;
  39.  
  40.   fp = fopen("filename.ext", "r");
  41.  
  42.   if (fp == NULL) puts("File not found");
  43. /*---------------------------------------*/
  44.  
  45.     If the filespec doesn't exist, fp will be set to NULL. If it does 
  46. exist, then fp will contain a non-NULL (non-zero) value.
  47.  
  48.